//
//  UICountButton.m
//  普安药房
//
//  Created by tianye on 16/5/4.
//  Copyright © 2016年 tianye. All rights reserved.
//

#import "ADCountButton.h"

const int myTime = 60;

@interface ADCountButton ()

@property (assign, nonatomic) int time;
@property (strong, nonatomic) NSTimer *timer;

@end

@implementation ADCountButton
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
    }
    return self;
}

/**
 *  开始倒计时
 */
- (void)startCountDown {
    self.enabled = NO;
    
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    self.time = myTime;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    [self countDown];
}

/**
 *	刷新[获取验证码] 按钮的计数
 */
- (void)countDown
{
    if (self.time <= 0) {
        [self endCountDown];
    } else {
        [self setTitle:[NSString stringWithFormat:@"剩余%d秒", self.time] forState:UIControlStateDisabled];
        self.time -= 1;
    }
}

/**
 *  结束倒计时
 */
- (void)endCountDown {
    self.enabled = YES;
    self.time = myTime;
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    
    if ([self.delegate respondsToSelector:@selector(countButtoneEndCountDown)]) {
        [self.delegate countButtoneEndCountDown];
    }
}



@end
